#include "base.h"
#include "napi/native_api.h"
#include <exception>

#ifndef HAR_OPEN_H
#define HAR_OPEN_H
struct OpenCallbackData {
    napi_async_work asyncWork;
    napi_deferred deferred;
    napi_ref callback;
    char *name;
    char *path;
    int result;
};

static void OpenExecute(napi_env env, void *data) {
    int result = 0;
    OpenCallbackData *callbackData = reinterpret_cast<OpenCallbackData *>(data);
    try {
        instance = ddjvu_context_create(callbackData->name);
        if (instance != NULL) {
            ddjvu_cache_set_size(instance, CACHE_SIZE);
            document = ddjvu_document_create_by_filename_utf8(instance, callbackData->path, 1);
            if (document == NULL) {
                ddjvu_context_release(instance);
            } else {
                result = 1;
            }
        }
    } catch (std::exception &e) {
    }
    callbackData->result = result;
}

static void OpenComplete(napi_env env, napi_status status, void *data) {
    OpenCallbackData *callbackData = reinterpret_cast<OpenCallbackData *>(data);
    napi_value result = nullptr;
    napi_create_int32(env, callbackData->result, &result);
    napi_resolve_deferred(env, callbackData->deferred, result);
    napi_delete_async_work(env, callbackData->asyncWork);
    delete callbackData;
}
#endif
